<template>
  <PageContainer title="产品查询" :showBack="false">
    <div class="mb-4">
      <a-form :model="formQuery" layout="inline">
        <a-form-item label="选择类别" required>
          <a-select v-model="formQuery.dl" placeholder="请选择类别" style="width: 328px" :options="typeOptions" @change="handleDlChange" allow-search></a-select>
        </a-form-item>
        <a-form-item label="选择产品" required>
          <a-space>
            <a-input v-model="keyword" placeholder="产品搜索" @blur="handleSearch"></a-input>
            <a-select
              v-model="formQuery.mc"
              style="width: 328px"
              :options="mcOptions"
              :loading="getOptionsLoading"
              placeholder="请选择产品"
              @change="handleChange"
              :virtual-list-props="{ height: 150 }"
            >
              <template #footer>
                <div style="padding: 8px 0; display: flex; align-items: center; justify-content: center">
                  <a-pagination
                    v-model:page-size="optionsPageSize"
                    v-model:current="optionsCurrent"
                    :total="optionsTotal"
                    simple
                    show-page-size
                    @change="() => handleSearch()"
                    @page-size-change="() => handleSearch()"
                    :page-size-options="[500, 1000, 5000]" 
                  />
                </div>
              </template>
            </a-select>
          </a-space>
          
        </a-form-item>
      </a-form>
    </div>
    <div v-if="formQuery.mc && data.length">
      <a-card>
        <div class="flex mb-4 justify-between items-center">
          <div><strong style="font-size: 20px">{{ formQuery.mc }}</strong></div>
          <a-space>
            <a-tooltip>
              <template #content>
                基于查询企业进项、销项的发票数据分析。<br />
                进项是指售卖方，销项是指购买方，商品大<br />
                类和小类名称是基于税务发票“货物名称”<br />
                分类，数量、金额、税收都来源于发票信<br />
                息。<br />
              </template>
              <icon-question-circle size="16" style="color: #A3B0CC" />
            </a-tooltip>
            <a-button @click="handleDetail">数据分析</a-button>
          </a-space>
        </div>
        <div class="mb-4">
          <PanelCollapse :input-list="inputList" :output-list="outputList"></PanelCollapse>
        </div>
        <div>
          <a-table
            :data="data"
            :columns="tableColumns"
            column-resizable
            :bordered="{ cell: true }"
            :loading="getTableLoading"
            :pagination="tablePagination"
            :scroll="{ x: '100%', y: '100%' }"
            @page-change="pageChange"
            @page-size-change="pageSizeChange"
          >
            <template #cgSfbdfp="{ record }">
              <a-tag v-if="record?.cg?.sfbdfp" :color="record?.cg?.sfbdfp === '本地' ? 'blue' : ''" v-tip>
                {{ record?.cg?.sfbdfp === '本地' ? '本地购入' : '外地购入' }}
              </a-tag>
              <span v-else> - </span>
            </template>
            <template #xxSfbdfp="{ record }">
              <a-tag v-if="record?.xx?.sfbdfp" :color="record?.xx?.sfbdfp ? 'blue' : ''" v-tip>
                {{ record?.xx?.sfbdfp === '本地' ? '销往本地' : '销往外地' }}
              </a-tag>
              <span v-else> - </span>
            </template>
          </a-table>
        </div>
      </a-card>
    </div>
    <div v-else style="height: 100%" class="flex items-center">
      <a-empty description="暂无数据，查询企业后，将在此处展示查询结果"></a-empty>   
    </div>
  </PageContainer>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import PageContainer from '@/components/PageContainer/index.vue';
import PanelCollapse from '@/components/PanelCollapse.vue';
import { useRouter } from 'vue-router';
import { formatWithThousandSeparator } from '@/utils';
import { getCpCxPage, getCplxList, getCpJybh, getCpYnbbh, getCpxllxPage } from '@/api/productInquiry';

const router = useRouter();
const inputList = ref({
  label: '已内部闭环',
  list: []
});
const outputList = ref({
  label: '建议内部闭环',
  list: []
});
const data = ref([]);
const formQuery = ref({
  mc: '',
  dl: ''
});
const allOptions = ref({});
const typeOptions = ref([]);
const getTableLoading = ref(false);
const getOptionsLoading = ref(false);
const tableColumns = ref([
  {
    title: '采购',
    children: [
      {
        title: '公司名称',
        dataIndex: 'cgMc',
        ellipsis: true,
		    tooltip: true
      },
      {
        title: '购入类型',
        width: 100,
        dataIndex: 'cgSfbdfp',
        slotName: 'cgSfbdfp'
      },
      {
        title: '数量',
        align: 'right',
        dataIndex: 'cgSl',
        ellipsis: true,
		    tooltip: true
      },
      {
        title: '金额',
        align: 'right',
        dataIndex: 'cgJe',
        ellipsis: true,
		    tooltip: true
      },
      {
        title: '税收',
        align: 'right',
        dataIndex: 'cgSe',
        ellipsis: true,
		    tooltip: true
      }
    ]
  },
  {
    title: '销售',
    children: [
      {
        title: '公司名称',
        dataIndex: 'xxMc',
        ellipsis: true,
		    tooltip: true
      },
      {
        title: '购入类型',
        width: 100,
        dataIndex: 'xxSfbdfp',
        slotName: 'xxSfbdfp'
      },
      {
        title: '数量',
        align: 'right',
        dataIndex: 'xxSl',
        ellipsis: true,
		    tooltip: true
      },
      {
        title: '金额',
        align: 'right',
        dataIndex: 'xxJe',
        ellipsis: true,
		    tooltip: true
      },
      {
        title: '税收',
        align: 'right',
        dataIndex: 'xxSe',
        ellipsis: true,
		    tooltip: true
      }
    ]
  }
]);
const tablePagination = ref({
  total: 0,
  showTotal: true,
  showJumper: true,
  showPageSize: true,
  current: 1,
  pageSize: 10
});

const optionsPageSize = ref(500);
const optionsCurrent = ref(1);
const optionsTotal = ref(100000);
const keyword = ref('');
const mcOptions = ref([]);

function handleSearch() {
  getOptionsLoading.value = true;
  getCpxllxPage({
    dl: formQuery.value.dl,
    keyword: keyword.value,
    pageNo: optionsCurrent.value,
    pageSize: optionsPageSize.value
  }).then((res) => {
    const { records, total } = res;
    optionsTotal.value = total;
    mcOptions.value = records.filter((item) => item);
  }).finally(() => {
    getOptionsLoading.value = false;
  });
}

function handleDlChange() {
  formQuery.value.mc = '';
  keyword.value = '';
  mcOptions.value = [];
  handleSearch();
}

// 已内部闭环
function getInputList() {
  getCpYnbbh({ ...formQuery.value }).then((res) => {
    inputList.value = { label: '已内部闭环', list: res };
  });
}

// 建议闭环
function getOutputList() {
 getCpJybh({ ...formQuery.value }).then((res) => {
    outputList.value = { label: '建议内部闭环', list: res };;
  });
}

// 获取所有类型
function getCplxListOptions() {
  getCplxList().then((res) => {
    allOptions.value = res || {};
    typeOptions.value = allOptions.value;
  });
}

function getTableList() {
  getTableLoading.value = true
  getCpCxPage({
    ...formQuery.value,
    pageNo: tablePagination.value.current,
    pageSize: tablePagination.value.pageSize
  }).then((res) => {
    const { records, total } = res;
    tablePagination.value.total = total;
    data.value = records.map((item) => {
      console.log(item?.cg?.se);
      return { 
        ...item,
        cgMc: item?.cg?.mc || '-',
        cgSl: item?.cg?.sl || '-',
        cgJe: formatWithThousandSeparator(item?.cg?.je || 0),
        cgSe: formatWithThousandSeparator(item?.cg?.se || 0),
        xxMc: item?.xx?.mc || '-',
        xxSl: item?.xx?.sl || '-',
        xxJe: formatWithThousandSeparator(item?.xx?.je || 0),
        xxSe: formatWithThousandSeparator(item?.xx?.se || 0),
      };
    });
  }).finally(() => {
    getTableLoading.value = false;
  });
}

function pageChange(val) {
  tablePagination.value.current = val
  getTableList()
}
function pageSizeChange(val) {
  tablePagination.value.pageSize = val
  getTableList()
}

function handleDetail() {
  router.push({ name: 'ProductInquiryDetail', query: { ...formQuery.value } })
}

function handleChange() {
  if (!formQuery.value.mc) return;
  tablePagination.value.current = 1;
  getTableList();
  getInputList();
  getOutputList();
}

onMounted(() => {
  handleChange();
  getCplxListOptions();
})
</script>

<style lang="less" scoped>
.tag {
  display: inline-block;
  max-width: 100%; 
  color: var(--color-text-2);
  padding: 1px 4px;
  font-size: 12px;
  border-radius: 4px;
}
</style>

<script>
export default {
  name: 'ProductInquiry'
}
</script>
